<template>
  <div class="wrapper"
       ref="wrapper">
    <div class="content">
      <div class="pull-down"
           v-if="pullDown">
        <div class="pull-down-res pull-down-text"
             v-if="pullInfo.pullDownEnd">释放更新</div>
        <div class="pull-down-no pull-down-text"
             v-if="pullInfo.pullDownStart && !pullInfo.pullDownEnd">下拉加载更多</div>
      </div>
      <slot></slot>
    </div>
    <slot name="noScrol"></slot>
  </div>
</template>
<script>
import BScroll from '@better-scroll/core'
const THRESHOLD = 70
export default {
  props: {
    dataResource: {
      type: Array,
      default: () => []
    },
    probeType: {
      type: Number,
      default: 3
    },
    click: {
      type: Boolean,
      default: true
    },
    listenScroll: {
      type: Boolean,
      default: true
    },
    pullDown: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      pullInfo: {
        pullDownEnd: false,
        pullDownStart: true
      }
    }
  },
  methods: {
    _initScroll () {
      this.scroll = new BScroll(this.$refs.wrapper, {
        probeType: this.probeType,
        click: this.click
      })
      if (this.listenScroll) {
        this.scroll.on('scroll', (e) => {
          this.$emit('onScroll', e)
        })
      }
      if (this.pullDown) {
        this.scroll.on('scroll', e => {
          if (e.y >= THRESHOLD) {
            this.pullInfo.pullDownEnd = true
            this.pullInfo.pullDownStart = false
          } else {
            this.pullInfo.pullDownStart = true
            this.pullInfo.pullDownEnd = false
          }
        })
      }
      if (this.pullDown) {
        this.scroll.on('touchEnd', (e) => {
          if (e.y >= THRESHOLD) {
            this.$emit('pulldown', e)
          }
        })
      }
    },
    refresh () {
      this.scroll && this.scroll.refresh()
    },
    scrollTo () {
      this.scroll && this.scroll.scrollTo.apply(this.scroll, arguments)
    },
    scrollToElement () {
      this.scroll && this.scroll.scrollToElement.apply(this.scroll, arguments)
    }
  },
  mounted () {
    this.$nextTick(() => {
      this._initScroll()
    })
  },
  watch: {
    dataResource () {
      this.$nextTick(() => {
        // 等待数据完毕过后强行更新better-scroll
        this.scroll.refresh()
      })
    }
  },
  beforeDestroyed () {
    this.scroll && this.scroll.destroy()
  }
}
</script>
<style scoped lang = 'scss'>
.pull-down {
  transform: translate3d(0, -100%, 0);
  position: absolute;
  width: 100%;
  padding: 10px 0;
}
.pull-down-text {
  text-align: center;
}
.content {
  position: relative;
}
</style>
